package com.liuwei.classy.util;

import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by loni on 2017/3/17.
 */
public class VZyEsEngine {
    private static Client client;
    private static VZyEsEngine esEngine;
    private static BulkProcessor experienceProcessor;
    public static final int ES_INDEX = 1;
    public static final int ES_TYPE = 2;
    public static final int ES_DOC = 3;

    public static VZyEsEngine getInstance() {
        if (esEngine == null) {
            esEngine = new VZyEsEngine();
            esEngine.initClient();
        }
        return esEngine;
    }

    public Client getClient() {
        if (client == null) {
            initClient();
        }
        return client;
    }

    public BulkProcessor getExperienceProcessor(){
        if (experienceProcessor==null){
            experienceProcessor= BulkProcessor.builder(getClient(), new BulkProcessor.Listener() {
                @Override
                public void beforeBulk(long l, BulkRequest bulkRequest) {

                }

                @Override
                public void afterBulk(long l, BulkRequest bulkRequest, BulkResponse bulkResponse) {

                }

                @Override
                public void afterBulk(long l, BulkRequest bulkRequest, Throwable throwable) {

                }
            }).setBulkActions(10).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.MB)).setFlushInterval(TimeValue.timeValueSeconds(10)).build();
        }
        return experienceProcessor;
    }

    /**
     * 初始化ES-Client
     */
    private void initClient() {
      /*  Settings settings = Settings.builder().put("client.transport.sniff", true).put("client", true).put("data", false).put("cluster.name", SelfConfigurerHolder.getProperty("es_cluster_name")).build();
        try {
              client = new PreBuiltTransportClient(Settings.EMPTY).
                    addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName((String) CustomizedPlaceholderConfigurer.getContextProperty("es_ip2")), Integer.valueOf((String) CustomizedPlaceholderConfigurer.getContextProperty("es_port"))));

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }*/
    }


    }
